<?php
/**
 * 命令行调用
 *
 * @example php /www/yaf/public/start.php request_uri=/index/rabbitPublisher
 *
 * Created by pangyiguang.
 * User: pangyiguang
 * Date: 2019/12/9
 * Time: 18:12
 */

use Yaf\Registry;

if (PHP_SAPI != 'cli') {
    exit('command error' . PHP_EOL);
}

date_default_timezone_set('Asia/Shanghai');
define('APPLICATION_PATH', dirname(dirname(__FILE__)));

$app = new \Yaf\Application(APPLICATION_PATH . '/conf/application.ini', ini_get('yaf.environ'));
//$app->bootstrap()->getDispatcher()->dispatch(new \Yaf\Request\Simple());

if (empty($argv[1])) {
    outPut('no command input');
    exit;
}

$params = $argv;

try {
    $app->bootstrap()->execute(function () use ($params) {
        $command = new \Yaf\Config\Ini(APPLICATION_PATH . '/conf/command.ini', 'common');
        $command = $command->toArray();

        if (!$command) {
            throw new Exception('no commands setting');
        }

        $command = $command['command'];

        $command = $command[$params[1]] ?? null;

        if (empty($command)) {
            throw new Exception('command: ' . $params[1] . ' not exists');
        }

        array_shift($params);

        $commandName = array_shift($params);

        $commandInfo = [
            'command' => $commandName,
            'params' => $params
        ];

        Registry::set('commandInfo', $commandInfo);

        $filePath = APPLICATION_PATH . DIRECTORY_SEPARATOR . '/application/modules/Cli/' . $command['class'] . '.php';

        if (!file_exists($filePath)) {
            outPut('file(' . $filePath . ') not exists');
        }

        require $filePath;

        $class = 'Cli\\' . $command['class'];

        if (is_callable($class)) {
            $class = call_user_func($class);
        }
        $startTime = microtime(true);
        outPut("command {$commandName} start.");

        call_user_func_array([$class, $command['method']], $params);

        $execTime = (microtime(true) - $startTime);

        outPut("command {$commandName} end, exec time: $execTime");
    });

} catch (Exception $exception) {
    outPut('Exception: ' . $exception->getMessage());
}


function outPut($butter)
{

    if (is_array($butter)) {
        $butter = json_encode($butter, JSON_UNESCAPED_UNICODE);
    }

    echo date('Y-m-d H:i:s', time()), ' ', $butter, PHP_EOL;
}